package entity

import (
	"QImages/database"
	"github.com/jinzhu/gorm"
)
// User 用户信息，与数据库中users表相对应
type User struct {
	gorm.Model
	Username  string
	Password  string
	Token     string
	Name      string
	AvatarUrl string
	Images    []Image   `gorm:"ForeignKey:UserID;AssociationForeignKey:ID"`
	Comments  []Comment `gorm:"ForeignKey:UserID;AssociationForeignKey:ID"`
}

func init() {
	database.DB.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4").AutoMigrate(&User{})
}

// Users 列出数据库中所有用户
func Users() (users []User, err error) {
	if err = database.DB.Find(&users).Error; err != nil {
		return
	}
	return
}

// CheckUser 判断用户名和密码是否匹配
func CheckUser(user *User) (err error) {
	find := database.DB.Where("username = ? AND password = ?", user.Username, user.Password).Find(&user)
	if err = find.Error; err != nil {
		return
	}
	return
}
// FindUserByToken 根据token查询用户信息
func FindUserByToken(token string) (user User, err error) {
	if err = database.DB.Where("token = ?", token).Find(&user).Error; err != nil {
		return
	}
	return
}
// FindUserById 根据用户id查询用户信息
func FindUserById(id uint) (user User, err error) {
	if err = database.DB.Where("id = ?", id).Find(&user).Error; err != nil {
		return
	}
	return
}
// Insert 插入一条用户信息
func (user User) Insert() (id uint, err error) {
	//添加数据
	result := database.DB.Create(&user)
	id = user.ID
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}
